package main

import (
	. "encoding/json"
	"fmt"
)

// 嵌套结构体 到 Json的互相转换

// 定义一个Student结构体
type Student struct {
	Id     int
	Gender string
	Name   string
}

// 定义一个班级结构体
type Class struct {
	Title    string
	Students []Student
}

func main() {
	var class = Class{
		Title:    "1班",
		Students: make([]Student, 0),
	}
	for i := 0; i < 10; i++ {
		s := Student{
			Id:     i + 1,
			Gender: "男",
			Name:   fmt.Sprintf("stu%v", i+1),
		}
		class.Students = append(class.Students, s)
	}
	fmt.Println(class)
	v, _ := Marshal(class)
	jsonStr := string(v)
	fmt.Println(jsonStr)

	var s2 = Class{}
	err := Unmarshal([]byte(jsonStr), &s2)
	if err != nil {
		fmt.Println("转换失败")
		return
	} else {
		fmt.Println(s2)
	}
}
